package com.ctrip.ibu.member.nameservice.timetask;


import com.ctrip.ibu.member.common.util.HttpClientUtil;
import com.ctrip.ibu.member.nameservice.controller.NameServerController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.Set;

/**
 *
 * 定时拉去每个broker的存活状态， 更新存活状态信息
 *
 * @author he.shaorong
 * @create 2023/3/20 19:19
 * @since 1.0.0
 */
@Configuration
@EnableScheduling
public class ScheduledTask {

    private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);


    public static final String IS_ACTIVE = ":8082/isActive";

    /**
     * 添加定时任务, 每隔1s执行一次
     */
    @Scheduled(cron = "0/30 * * * * ?")
    @Scheduled(fixedRate=5000)
    private void configureTasks() {
        Set<String> allAiveIpList = NameServerController.getAliveIpList();
        logger.info("broker scan time: " + LocalDateTime.now());
        logger.info("broker scan allAiveIpList: " + allAiveIpList.toString());

        for(String ip: allAiveIpList) {
            boolean isBrokeAlive = isBrokerAlive(ip);
            if(!isBrokeAlive) {
                allAiveIpList.remove(ip);
            }
        }
    }

    private boolean isBrokerAlive(String ip) {
        try {
            String checkBrokerUrl = "http://"+ ip+ IS_ACTIVE;
            HttpClientUtil.get(checkBrokerUrl);
            logger.info("scan broker ip alive success" + ip);
            return true;
        } catch (Exception e) {
            logger.error("scan broker ip alive error: " + e);
            return false;
        }
    }
}
